#!/usr/bin/python

from datetime import datetime, date
import arrow


def day_begin_end_of_month(
        target=None, fmt=None,
        years_shift=0, months_shift=0, weeks_shift=0, days_shift=0
):
    """
    返回指定日期所在月份的第一天和最后一天
    :param target: 指定的目标时间点，默认当前时间
    :param fmt:
    :param years_shift:
    :param months_shift:
    :param weeks_shift:
    :param days_shift:
    :return:
    """
    arw = arrow.now()
    arw_new = arw.clone()
    if target is not None:
        arw_new = arw.fromdatetime(target)
    arw_new = arw_new.shift(
        years=years_shift, months=months_shift, weeks=weeks_shift, days=days_shift
    )

    arw_begin = arrow.Arrow(arw_new.year, arw_new.month, 1)

    arw_end = arw_begin.shift(months=1)
    arw_end = arw_end.shift(days=-1)

    return arw_begin.format(fmt), arw_end.format(fmt), arw_new.format(fmt), arw.format(fmt)


def get_month_val(this_date=None) -> int:
    """
    获取指定时间的月份
    :param this_date: 指定时间对象 默认为当前时间
    :return: int 月份值
    """
    if this_date is None:
        this_date = datetime.now()
    return this_date.month


def get_month_apart(from_date, to_date=None) -> int:
    """
    获取两个时间对象，相差的月份数，精确到天
    :param from_date: 开始日期 可以是日期或时间对象 必传
    :param to_date: 结束日期 可以是日期或时间对象 默认当前日期
    :return: int 月份数
    """
    if to_date is None:
        to_date = datetime.now()
    if not isinstance(from_date, datetime) and not isinstance(from_date, date):
        from_date = datetime.strptime(from_date, "%Y-%m-%d")
    if not isinstance(to_date, datetime) and not isinstance(to_date, date):
        to_date = datetime.strptime(to_date, "%Y-%m-%d")
    from_year = from_date.year
    from_month = from_date.month
    from_day = from_date.day
    to_year = to_date.year
    to_month = to_date.month
    to_day = to_date.day
    months = to_year * 12 + to_month - (from_year * 12 + from_month)
    if from_month == to_month and from_day > to_day:
        months -= 1
    return months
